package com.qxsx.midi.adapter;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.qxsx.midi.R;
import com.qxsx.midi.activity.home.BuyListActivity;
import com.qxsx.midi.activity.home.CourseDetailsActivity;
import com.qxsx.midi.activity.home.MusicDetailsActivity;
import com.qxsx.midi.activity.me.MeKejiantActivity;
import com.qxsx.midi.config.AppContext;
import com.qxsx.midi.model.Buy;
import com.qxsx.midi.utils.CustomProgress;
import com.qxsx.midi.utils.MyNet;
import com.qxsx.midi.utils.SPUtils;
import com.qxsx.midi.utils.Tools;
import com.qxsx.midi.utils.callBackJsonArray;
import com.qxsx.midi.utils.callBackNull;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Zrj on 2015/9/6.
 */
public class BuyAdapter extends BaseAdapter {
    private CustomProgress customProgress;
    Dialog dialog;
    List<Buy> list = new ArrayList<>();
    private LayoutInflater inflater;
    private Context context;
    private Activity activity;
    String order_id, order_code;
    String flag;
    Handler handler;
    String login_name;

    public BuyAdapter(Context context, List<Buy> list, Activity activity, Handler handler) {
        this.context = context;
        this.list = list;
        this.activity = activity;
        this.handler = handler;
        inflater = LayoutInflater.from(context);
    }

    //动态添加数据
    public void addData(List<Buy> addlist) {//刷新数据
        for (Buy buy : addlist) {
            list.add(buy);
        }
        notifyDataSetChanged();
    }

    // 清空所有
    public void removeAll() {
        list.clear();
        notifyDataSetChanged();
    }


    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public Object getItem(int position) {
        return list.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    /**
     * 订单
     */

    private void orderr(String id, String type, final String name, final String price, final String file_url) {
        customProgress = CustomProgress.show(activity, "请稍后....", true, null);

        JSONObject object = new JSONObject();
        JSONArray array = new JSONArray();
        String user_id = (String) SPUtils.get(AppContext.getContext(), "user_id", "");
        try {

            object.put("material_id", id);
            object.put("type", type);
            object.put("user_id", user_id);
            object.put("price", price);
            array.put(object);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        MyNet.doPostJsonArray("405", array, new callBackJsonArray() {
            @Override
            public void run(Object code, Object message, JSONArray array) {
                try {
                    JSONObject object1 = array.getJSONObject(0);
                    order_id = object1.getString("order_id");
                    order_code = object1.getString("order_code");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                customProgress.dismiss();
                dialogbuy(name, price, file_url);
            }
        });


    }

    /**
     * 支付的dialog
     */
    private void dialogbuy(final String name, final String price, final String file_url) {

        LayoutInflater layout = LayoutInflater.from(AppContext.getContext());
        View view = layout.inflate(R.layout.dialog_buy_item, null);
        dialog = new AlertDialog.Builder(activity).create();
        TextView tv_zhifu = (TextView) view.findViewById(R.id.tv_zhifu);
        TextView tv_weixin = (TextView) view.findViewById(R.id.tv_weixin);

        /**
         * 支付宝支付
         */
        tv_zhifu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Tools.AliPayInfo info = new Tools.AliPayInfo("迷笛考级", name, price);
                Tools.WeiXinPayInfo info1 = new Tools.WeiXinPayInfo(order_code, (int) (Float.parseFloat(price) * 100),name);
                info.OrderCode = order_code;
                Tools.Pay(info1, info, activity, "支付宝", new callBackNull() {
                            @Override
                            public void run() {
                                flag = "1";
                                wreslust();
                                dialog.dismiss();
                                dialogfinish(file_url);
                            }
                        }, new callBackNull() {
                            @Override
                            public void run() {
                                flag = "0";
                                wreslust();
                                Toast.makeText(activity, "支付失败", Toast.LENGTH_SHORT).show();
                                dialog.dismiss();
                            }
                        },
                        null
                );
            }
        });
        /**
         * 微信支付
         */
        tv_weixin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Tools.AliPayInfo info = new Tools.AliPayInfo("迷笛考级", name, price);
                Tools.WeiXinPayInfo info1 = new Tools.WeiXinPayInfo(order_code, (int) (Float.parseFloat(price) * 100),name);
                info.OrderCode = order_code;
                Tools.Pay(info1, info, activity, "微信", new callBackNull() {
                            @Override
                            public void run() {
                                flag = "1";
                                wreslust();
                                dialog.dismiss();
                                dialogfinish(file_url);
                            }
                        }, new callBackNull() {
                            @Override
                            public void run() {
                                flag = "0";
                                wreslust();
                                Toast.makeText(activity, "支付失败", Toast.LENGTH_SHORT).show();
                                dialog.dismiss();
                            }
                        },
                        null
                );


            }
        });
        TextView tv_clance = (TextView) view.findViewById(R.id.tv_clance);
        tv_clance.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });

        DisplayMetrics dm = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
        int x = dm.widthPixels;// 屏幕的宽
        int y = dm.heightPixels;// 屏幕的宽
        dialog = new Dialog(activity, R.style.dialog);
        dialog.getWindow().setLayout((int) (x / 2.2), (int) (y / 1.8));
        dialog.show();
        dialog.setContentView(view);
        dialog.setCancelable(false);


    }


    /**
     * 支付完成的dialog
     */
    private void dialogfinish(final String file_url) {
        LayoutInflater layout = LayoutInflater.from(AppContext.getContext());
        View view = layout.inflate(R.layout.dialog_buy_finish, null);
        dialog = new AlertDialog.Builder(activity).create();
        Button btn_see = (Button) view.findViewById(R.id.btn_see);
        Button btn_clance = (Button) view.findViewById(R.id.btn_cancel);
        btn_clance.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                handler.sendEmptyMessage(BuyListActivity.WHAT_INITDATA);
                dialog.dismiss();

            }
        });
        btn_see.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                handler.sendEmptyMessage(BuyListActivity.WHAT_INITDATA);
                Intent it = new Intent(activity, MeKejiantActivity.class);
                it.putExtra("file_url", file_url);//传递商家ID
                activity.startActivity(it);
                dialog.dismiss();
            }
        });
        DisplayMetrics dm = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
        int x = dm.widthPixels;// 屏幕的宽
        int y = dm.heightPixels;// 屏幕的高
        dialog = new Dialog(activity, R.style.dialog_finish);
        dialog.getWindow().setLayout((int) (x / 2.2), (int) (y / 1.8));
        dialog.show();
        dialog.setContentView(view);
        dialog.setCancelable(false);


    }

    /**
     * 记录支付结果
     */
    private void wreslust() {
        customProgress = CustomProgress.show(activity, "请稍后....", true, null);

        JSONObject object = new JSONObject();
        JSONArray array = new JSONArray();

        try {
            object.put("order_id", order_id);
            object.put("flag", flag);
            array.put(object);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        MyNet.doPostJsonArray("404", array, new callBackJsonArray() {
            @Override
            public void run(Object code, Object message, JSONArray array) {
                customProgress.dismiss();
            }
        });


    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            holder = new ViewHolder();
            convertView = inflater.inflate(R.layout.buy_list_item, null);
            holder.iv_img = (ImageView) convertView.findViewById(R.id.iv_img);
            holder.tv_name = (TextView) convertView.findViewById(R.id.tv_name);
            holder.tv_price = (TextView) convertView.findViewById(R.id.tv_price);
            holder.btn_buy = (Button) convertView.findViewById(R.id.btn_buy);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        final Buy buy = list.get(position);
        holder.tv_name.setText(buy.getBuy_name());
        holder.tv_price.setText(buy.getBuy_price());
        holder.iv_img.setImageResource(buy.getBuy_img());
        holder.btn_buy.setOnClickListener(new View.OnClickListener() {
                                              @Override
                                              public void onClick(View v) {
//                                                  login_name = (String) SPUtils.get(AppContext.getContext(), "login_name", "");
//                                                  if (login_name != "") {
//                                                      if (buy.getBuy_buy().equals("1")) {
//                                                          dialogfinish(buy.getBuy_url());
//                                                      } else {
//                                                          orderr(buy.getBuy_id(), buy.getBuy_tapy(), buy.getBuy_name(), buy.getBuy_price(), buy.getBuy_url());
//                                                      }
//                                                  } else {
//
//                                                      handler.sendEmptyMessage(BuyListActivity.WHAT_TIAOZHUAN);
//
//                                                  }
                                                  Toast.makeText(context,"该功能暂时无法使用",Toast.LENGTH_SHORT).show();


                                              }
                                          }

        );
        convertView.setOnClickListener(new View.OnClickListener() {
                                           @Override
                                           public void onClick(View v) {
                                               if (buy.getBuy_tapy().equals("1")) {
                                                   //跳转到商家详情页面
                                                   Intent it = new Intent(activity, MusicDetailsActivity.class);
                                                   it.putExtra("id", buy.getBuy_id());//传递商家ID
                                                   it.putExtra("type", buy.getBuy_tapy());//传递商家ID
                                                   it.putExtra("buy", buy.getBuy_buy());//传递是否购买
                                                   activity.startActivity(it);

                                               } else {
                                                   Intent it = new Intent(activity, CourseDetailsActivity.class);
                                                   it.putExtra("id", buy.getBuy_id());//传递商家ID
                                                   it.putExtra("type", buy.getBuy_tapy());//传递商家ID
                                                   it.putExtra("buy", buy.getBuy_buy());//传递是否购买

                                                   activity.startActivity(it);
                                               }


                                           }
                                       }

        );
        return convertView;

    }


    class ViewHolder {
        ImageView iv_img;
        TextView tv_name;
        TextView tv_price;
        Button btn_buy;
    }
}
